#include <qpixmap.h>    //qt中的类
#include <qtimer.h>
#include <QMessageBox>
#include "login.h"
#include "verifycodedialog.h"
#include "mainwindow.h"
#include <QByteArray>
#include <QInputDialog>
#include <qmovie.h>
#include <qdesktopwidget.h>
#include <qpalette.h>
#include "qtq_config.h"
#include "qqdef.hpp"
#include "qqclient.hpp"
#include <stdio.h>
#include <stdlib.h>
#include "debug.hpp"
#include <string.h>
#include <QDebug>
#include "db.h"

#ifdef _WINDOWS
#include <Windows.h>
#include <shellapi.h>
#pragma comment(lib,"shell32.lib")
#endif
extern bool isLoginSuccess;
extern bool isLoginCancel;
//extern int login(uint uid,const char* password,bool ishdden);
extern qqclient* qq;

extern MainWindow* wMain;
extern Login* wLogin;
extern bool soundState;
static int login(uint uid,const char* password,bool ishdden)
{
    DBG( "qqclient_create()" );
    qqclient_create( qq, uid, (char*)password );
    qq->mode = ishdden ? QQ_HIDDEN : QQ_ONLINE;
    DBG( "qqclient_login()" );
    if(qqclient_login( qq )!=0)
		return -1;
    DBG( "login() end" );
    return 0;
}
Login::Login(QWidget *parent) :
    QDialog(parent),status(0),sound(1)
{
    Ui::Login::setupUi(this);
    QDesktopWidget* desktop = QApplication::desktop();
    move((desktop->width() - width())/2, (desktop->height() - height())/2);

    txtUser->setText("");
    txtPass->setText("");
    db &infoDB = db::GetInstance();
    infoDB.open(0);
    infoDB.readAccount( accountList );
    QString account;
    if(!accountList.empty())
    {
        account = accountList[0];
        for(AccountList::size_type i =0; i < accountList.size();i++)
        {
            QString tmpAccount = accountList[i];
            QStringList tmpAcountlist = tmpAccount.split("\t",QString::SkipEmptyParts);
            if(tmpAcountlist.size()>1)
            {
                lstAccount->addItem(tmpAcountlist[0]);
            }
        }
    }

    QStringList acountlist = account.split("\t",QString::SkipEmptyParts);
    QString uid = "";
    QString pwd = "";
    if(acountlist.size()>1)
    {
        uid = acountlist[0];
        pwd = acountlist[1];
    }
    else
    {
        uid = account;
    }
    if(uid.size()>0)
    {
        txtUser->setText(uid);
        txtPass->setText(pwd);
    }

    txtUser->setFocus();
    progressBar->setVisible(false);

    btnCancel->setVisible(false);

    lstAccount->setVisible(false);

    btnSelectAccount->setFlat(true);
    btnSelectAccount->setText("");

    btnSelectAccount->setIconSize(QSize(20,16));

    btnSelectAccount->setIcon(QPixmap(RC_PREFIX "QQTheme/PowerTreeFlag2.png"));
    connect( btnSelectAccount, SIGNAL(clicked()),SLOT(SelectAccountClick()));
    connect( lstAccount, SIGNAL(currentRowChanged(int)),this,SLOT(OnSelectAccount(int)));

    connect(btnLogin, SIGNAL(clicked()),SLOT(loginClick()));
    connect(btnExit,SIGNAL(clicked()),SLOT(exitClick()));
    connect(btnCancel,SIGNAL(clicked()),SLOT(cancelClick()));

    timer = new QTimer(this);
    connect( timer, SIGNAL(timeout()), this, SLOT(timerDone()) );
    connect( this, SIGNAL(cancelLogin()),timer, SLOT(stop()) );

    connect( lblStatus, SIGNAL(Clicked(QClickedLabel*)),this, SLOT(lblNextStatusClicked(QClickedLabel*)) );

    connect( lblMode, SIGNAL(Clicked(QClickedLabel*)),this, SLOT(lblNextSettingClicked(QClickedLabel*)) );

    QPalette pal(QColor(255,255,255));
    pal.setColor( QPalette::Text, QColor(255,255,255) );
    pal.setColor( QPalette::Foreground, QColor(255,255,255) );

    lblStatus->setPalette(pal);
    lblMode->setPalette(pal);
}

void Login::lblNextStatusClicked(QClickedLabel* label)
{
    //static int status = 0;
    if(status == 0)
    {
        lblStatus->setText(QObject::tr("隐身"));
        status = 1;
    }
    else
    {
        lblStatus->setText(QObject::tr("在线"));
        status = 0;
    }
}

void Login::lblNextSettingClicked(QClickedLabel* label)
{
    //static int Setting = 0;
    if(sound == 0)
    {
        lblMode->setText(QObject::tr("有声模式"));
        sound = 1;
    }
    else
    {
        lblMode->setText(QObject::tr("安静模式"));
        sound = 0;
    }
    soundState = sound == 1;
}

void Login::changeEvent(QEvent *e)
{
    QDialog::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        retranslateUi(this);
        break;
    default:
        break;
    }
}
void Login::SelectAccountClick()
{
    lstAccount->setVisible( !lstAccount->isVisible() );
}

void Login::loginClick()
{
    showStage(1);
    QApplication::processEvents();
    int uid = txtUser->text().toInt();
    QByteArray bpass = txtPass->text().toLatin1();
    const char* spass = bpass.data();
    login(uid,spass,status == 1 ? true : false);
}

void Login::OnSelectAccount(int currentRow)
{
    QString account;
    if(accountList.size()>0)
    account = accountList[currentRow];

    QStringList acountlist = account.split("\t",QString::SkipEmptyParts);
    QString uid = "";
    QString pwd = "";
    if(acountlist.size()>1)
    {
        uid = acountlist[0];
        pwd = acountlist[1];
    }
    else
    {
        uid = account;
    }
    if(uid.size()>0)
    {
        txtUser->setText(uid);
        txtPass->setText(pwd);
    }
    lstAccount->setVisible(false);
}

void Login::showStage(int index)
{
    switch(index) // 0 login,1 logining,2 main
    {
    case 0:
        txtPass->setVisible(true);
        txtUser->setVisible(true);
        btnLogin->setVisible(true);
        btnCancel->setVisible(true);
        progressBar->setVisible(false);
        btnCancel->setVisible(false);
        btnExit->setVisible(true);
        btnSelectAccount->setVisible(true);

        lblLogining->setVisible(false);
        lblBG->setVisible(true);
        lblMode->setVisible(true);
        lblStatus->setVisible(true);

        timer->stop();
        break;
    case 1:
        btnSelectAccount->setVisible(false);
        txtPass->setVisible(false);
        txtUser->setVisible(false);
        btnLogin->setVisible(false);
        btnCancel->setVisible(true);
        progressBar->setVisible(true);
        btnExit->setVisible(false);
        lblBG->setVisible(false);
        lblLogining->setVisible(true);
        lblMode->setVisible(false);
        lblStatus->setVisible(false);

        timer->start(500); // 2秒单触发定时器
        break;
    case 2:
        break;
    }
}

void Login::timerDone()
{
#ifdef WINSCW
    timer->stop();
    emit LoginSuccess();
    close();
#endif

    int v = progressBar->value() + 10;
    if(v < 100)
    {
        progressBar->setValue( v);
    }
    else
    {
        progressBar->setValue(0);
    }
    isLoginSuccess = false;
    isLoginCancel = false;
    if( qq->process == P_LOGGING )
            return;
    if( qq->process == P_VERIFYING ){
        QString vfilepath = QString("%1/%2.png").arg(qq->verify_dir).arg(qq->number);
		verifycodeDialog dlg;
		dlg.setPixmap(vfilepath);
		dlg.exec();		
        //wLogin->onDisplayVerCode(vfilepath);
        timer->stop();
        QString sInput = dlg.getText();
        if ( !sInput.isEmpty() ) {
            QByteArray ba = sInput.toLatin1();
            char* input = ba.data();
            DBG("very code:%s",input);
            qqclient_verify( qq, input );
            //qqclient_wait( qq, 3 ); /*wait one second*/
            while( qq->process == P_LOGGING )
            {
                QApplication::processEvents();
                qqclient_wait( qq, 1 );
            }

            timer->start();
            return;
        }
        else
        {
            isLoginCancel = true;
        }
    }
    if( qq->process != P_LOGIN ){
            isLoginCancel = true;
            switch( qq->process ){
            case P_ERROR:
                    QMessageBox::critical(0,"critical",QObject::tr("网络错误."));
                    break;
            case P_DENIED:
                    QMessageBox::critical(0,"critical",QObject::tr("您的QQ需要激活(http://jihuo.qq.com)."));
#ifdef __WIN32__
                    ShellExecute(NULL,L"open",L"http://jihuo.qq.com/",NULL,NULL,SW_SHOWNORMAL);
#endif

                    break;
            case P_WRONGPASS:
                    QMessageBox::critical(0,"critical",QObject::tr("您的密码错误."));

                    break;
            }

    }
    else
    {
        isLoginSuccess = true;
        if(!qq->login_finish)
        {
            return;
        }
    }
    if(isLoginCancel)
    {
        showStage(0);
        QApplication::processEvents();
        qqclient_logout( qq );
        qqclient_cleanup( qq );

    }//判断是否登陆成功
    else if(isLoginSuccess)
    {
        //save qq number;
        db &infoDB = db::GetInstance();
        infoDB.open(0);
        QString uid = QString("%1").arg(qq->number);
        QString pass = txtPass->text();
        infoDB.writeAccount(uid,pass);

        infoDB.open(qq->number);
        
        timer->stop();
        emit LoginSuccess();
        close();
    }
}

void Login::cancelClick()
{
    emit cancelLogin();
    showStage(0);
}

void Login::exitClick()
{
    //QApplication::exit();
    close();
    wMain->close();
    QApplication::exit();
}
//void Login::createActions()
//{
//    actHidden = new QAction(tr("&Hidden"), this);
//    actHidden->setIcon();
//}
